package com.gengyun.gengyunacquistion.scheduled;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gengyun.gengyunacquistion.pojo.Indicator;
import com.gengyun.gengyunacquistion.service.IAcquisitionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@DisallowConcurrentExecution
public class DataAcquisition implements Job {

    @Autowired
   private IAcquisitionService acquisitionService;

    /**
     *  定时从接口获取数据的定时任务
     * @param jobExecutionContext
     * @throws JobExecutionException
     */
    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("正在进行任务1");
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

        // 初始化基本数据
        String lastTimestamp = acquisitionService.getLastTimestamp();
        String beginTimestamp = String.valueOf(Long.parseLong(lastTimestamp) + 1000L);



        System.out.println("lastTimestamp ====> "+lastTimestamp);
        System.out.println("beginTimestamp ====> "+beginTimestamp);
        String endTimestamp = String.valueOf(System.currentTimeMillis());

        if (Long.parseLong(endTimestamp) - Long.parseLong(beginTimestamp) > 2678400000L) {
            endTimestamp = String.valueOf(Long.parseLong(beginTimestamp) + 2678400000L);
        }

        System.out.println("begin ====> "+beginTimestamp);
        System.out.println("end ====> "+endTimestamp);



        log.info("数据接口获取数据开始 ====> "+sf.format(new Date()));

        /**
         * 下面是java爬虫的开始
         */
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();

        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        // 请求路径拼接
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder("https://api.simplanting.cn/trend/crop_indicator?");
            uriBuilder.setParameter("frequentness", "1");
            uriBuilder.setParameter("startTimestamp", beginTimestamp);
            uriBuilder.setParameter("endTimestamp", endTimestamp);
            uriBuilder.setParameter("indicatorIDs",
                    "264,265,270,271,272," +
                    "297,300,305,206,307," +
                    "308,314,315,316,321," +
                    "274,10035,10036,273,278," +
                    "279,280,295,319,320," +
                    "327,328,10044,10045," +
                    "10046,336,337,338," +
                    "335,334,333,10042,332," +
                    "331,330,329,10041,318," +
                    "293,10052,10058,10053,10055,10056,10057");
            uriBuilder.setParameter("cropsRotationPlotIDs", "16085, 16086, 16080, 16081, 16650, 16651, 16652, 16653, 16654");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        // Get请求
        HttpGet httpGet = null;
        try {
            httpGet = new HttpGet(uriBuilder.build());
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        // 设置请求头
        httpGet.setHeader("content-type", "application/json");
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Cache-Control", "no-cache");
        httpGet.setHeader("PDS-ESP-APP-TOKEN", "6a3d382c08f04f47b4303592c9ddb483\n");

        CloseableHttpResponse response = null;

        try {
            response = httpClient.execute(httpGet);
            String content = EntityUtils.toString(response.getEntity(), "utf8");
          // System.out.println(content);
//            System.out.println(jobExecutionContext.getScheduler().getCurrentlyExecutingJobs());
            // 执行语句处理json数据
         //  createJsonFile(content,"./test_Hourly.txt");
           acquisitionService.JsonHandler(content,endTimestamp);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("数据接口获取数据完毕 ====> "+sf.format(new Date()));
    }




    /**
     * 将json数据保存到txt文档中，
     * @Transactional(rollbackFor = Exception.class)
     * @param content  filePath
     */
    public static boolean createJsonFile(String content, String filePath) {

        // 标记文件生成是否成功
        boolean flag = true;
        // 生成json格式文件
        try {
            // 保证创建一个新文件
            File file = new File(filePath);
            if (!file.getParentFile().exists()) { // 如果父目录不存在，创建父目录
                file.getParentFile().mkdirs();
            }
            if (file.exists()) { // 如果已存在,删除旧文件
                file.delete();
            }
            file.createNewFile();
            // 将格式化后的字符串写入文件
            Writer write = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            write.write(content);
            write.flush();
            write.close();
        } catch (Exception e) {
            flag = false;
            e.printStackTrace();
        }
        return flag;
    }
}
